/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.stock.service.impl;

import me.zhengjie.jdbcLinkDb.JdbcToDbService;
import me.zhengjie.modules.stock.domain.Stock;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.stock.repository.StockRepository;
import me.zhengjie.modules.stock.service.StockService;
import me.zhengjie.modules.stock.service.dto.StockDto;
import me.zhengjie.modules.stock.service.dto.StockQueryCriteria;
import me.zhengjie.modules.stock.service.mapstruct.StockMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2021-10-14
**/
@Service
@RequiredArgsConstructor
public class StockServiceImpl implements StockService {

    private final StockRepository stockRepository;
    private final StockMapper stockMapper;

    @Resource
    private JdbcToDbService jdbcToDbService;

    @Override
    public Map<String,Object> queryAll(StockQueryCriteria criteria, Pageable pageable){
        Page<Stock> page = stockRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        jdbcToDbService.delStock();
        List<Stock> stocks = jdbcToDbService.getStock();
        for (Stock stock:stocks){
            System.out.println(stock.getStockName());
        }
        return PageUtil.toPage(page.map(stockMapper::toDto));
    }

    @Override
    public List<StockDto> queryAll(StockQueryCriteria criteria){
        return stockMapper.toDto(stockRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public StockDto findById(Long id) {
        Stock stock = stockRepository.findById(id).orElseGet(Stock::new);
        ValidationUtil.isNull(stock.getId(),"Stock","id",id);
        return stockMapper.toDto(stock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockDto create(Stock resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        jdbcToDbService.insertStock();
        return stockMapper.toDto(stockRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Stock resources) {
        Stock stock = stockRepository.findById(resources.getId()).orElseGet(Stock::new);
        ValidationUtil.isNull( stock.getId(),"Stock","id",resources.getId());
        stock.copy(resources);
        stockRepository.save(stock);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            stockRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StockDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StockDto stock : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("股票名称", stock.getStockName());
            map.put("股票类型", stock.getStockType());
            map.put("买入价格", stock.getBuyPrice());
            map.put("卖出价格", stock.getSellPrice());
            map.put("买入时间", stock.getBuyTime());
            map.put("卖出时间", stock.getSellTime());
            map.put("持有数量", stock.getHoldNum());

            map.put("赚取差价", stock.getEarnMoney());
            map.put("分享心得", stock.getShareMood());
            map.put("创建者", stock.getCreateBy());
            map.put("更新者", stock.getUpdateBy());
            map.put("创建日期", stock.getCreateTime());
            map.put("更新时间", stock.getUpdateTime());
            map.put("删除标记", stock.getDelFlag());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}